package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.config.SsoConfig;
import org.example.utils.JwtUtils;
import org.example.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Controller
public class AuthController {

    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SsoConfig ssoConfig;  // 配置类（需自己定义，映射sso.clients）

    // 存储已登录用户（实际应使用Redis等分布式存储）
    private Map<String, String> loggedUsers = new ConcurrentHashMap<>();

    // 跳转到登录页
    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) String clientId,
                            @RequestParam(required = false) String redirectUri,
                            Model model) {
        log.info("跳转登录页 clientId:{}, redirectUri:{}", clientId, redirectUri);

        model.addAttribute("clientId", clientId);
        model.addAttribute("redirectUri", redirectUri);
        return "login";  // 对应login.html
    }

    // 处理登录请求
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String clientId, String redirectUri, Model model, HttpServletRequest request) {
        log.info("处理登录请求 username: {}, password: {}, clientId: {}, redirectUri: {}", username, password, clientId, redirectUri);

        // 简单验证（实际应查数据库）
        if (!"admin".equals(username) || !"123456".equals(password)) {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }

        // 验证客户端合法性
        if (!ssoConfig.getClients().stream().anyMatch(c -> c.getClientId().equals(clientId)
                && c.getRedirectUri().equals(redirectUri))) {
            model.addAttribute("error", "非法客户端");
            return "login";
        }

        // 生成JWT令牌
        String token = jwtUtils.generateToken(username);
        loggedUsers.put(username, token);  // 记录登录状态
        log.info("登录用户列表：{}", loggedUsers);

        // 重定向到客户端并携带令牌
        return "redirect:" + redirectUri + "?token=" + token;
    }

    // 验证令牌接口（供客户端调用）
    @GetMapping("/validate")
    @ResponseBody
    public Map<String, Object> validateToken(String token) {
        log.info("校验token: {}", token);

        Map<String, Object> result = new HashMap<>();
        if (jwtUtils.validateToken(token)) {
            result.put("valid", true);
            result.put("username", jwtUtils.getUsernameFromToken(token));
        } else {
            result.put("valid", false);
        }
        return result;
    }

    // 退出登录
    @GetMapping("/logout")
    public String logout(String username, HttpServletRequest request) {
        log.info("退出登录 username: {}", username);

        // 1. 清除分布式存储中的登录记录（示例中用loggedUsers，实际用Redis）
        if (username != null) {
            loggedUsers.remove(username);
        }

        // 2. 清除当前session中的登录状态
        HttpSession session = request.getSession();
        if (session != null) {
            // 移除session中存储的token
            session.removeAttribute("token");
            // 让session立即失效（彻底清除会话）
            session.invalidate();
        }
        return "redirect:/login";
    }
}
